package com.qf.microuser.user.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qf.common.core.entity.User;
import com.qf.common.core.ex.BusinessException;
import com.qf.microuser.user.pojo.dto.UserDTO;
import com.qf.microuser.user.mapper.UserMapper;
import com.qf.microuser.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;
    /*
    * 注册
    * 1）对参数进行校验
    *   1.1) 校验参数是否为空
    *   1.2) 校验用户名和手机号是否重复
    * 2) 验证码
    * 3) 是否有邀请码
    * */

    @Override
    public void register(UserDTO userDTO) {
        // 手机号是null或者是"",或者 长度不等于11 -->格式不正确
        if (!StringUtils.hasText(userDTO.getPhone()) || userDTO.getPhone().length() != 11) {
            throw new BusinessException("手机号格式不正确");
        }

        // 判断密码
        if (!StringUtils.hasText(userDTO.getPassword())) {
            throw new BusinessException("密码不能为空!");
        }

        // 用户名重复校验...
        LambdaQueryWrapper<User> lambdaQuery = Wrappers.lambdaQuery(User.class);
        lambdaQuery.eq(User::getUsername, userDTO.getUsername());
        boolean exists = userMapper.exists(lambdaQuery);// 有该用户名的对象,返回就是true
        if (exists) {
            // 不为空,即存在该用户名,不让注册
            throw new BusinessException("用户名已存在!");
        }

        // 验证码...TODO

        // 邀请码...TODO

        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        if (StringUtils.hasText(userDTO.getInviteCode())) { // 有邀请码
            User parentUser = userMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getInviteCode, userDTO.getInviteCode()));
            // 根据邀请码查不出人
            if (ObjectUtils.isEmpty(parentUser)){
                throw new BusinessException("邀请码有误!");
            }

            Integer pid = parentUser.getId();
            user.setPid(pid);

            // 产生6位随机数
            String newInviteCode = RandomUtil.randomString(6);
            user.setInviteCode(newInviteCode);
        }

        userMapper.insert(user);
    }
}
